<template>
  <div>
    <el-card>
      <!-- 添加商品按钮 -->
      <el-button type="primary" icon="Plus" @click="addTrademark" v-has="`btn.Trademark.add`">添加品牌</el-button>
      <!-- 表格组件展示已有商品数据 -->
      <!-- table
            border 纵向是否有边框 
            column
              width 列宽度
              align 文字排列规则
              label 列名
       -->
      <el-table style="margin: 10px 0px;" border :data="trademarkArr">
        <el-table-column width="80px" align="center" label="序号" type="index"></el-table-column>
        <!-- tablecolunm:默认用div展示数据  可以用插槽 -->
        <!-- <el-table-column label="品牌名称" prop="tmName"></el-table-column> -->
        <el-table-column label="品牌名称">
          <template #="{ row, $index }">
            <pre>{{ row.tmName }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <img :src="row.logoUrl" style="width: 100px; height: 100px;">
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, $index }">
            <el-button @click="updateTrademark(row)" type="primary" size="small" icon="Edit"></el-button>
            <el-popconfirm :title="`是否删除${row.tmName}?`" width="250px" icon="Delete" @confirm="removeTradeMark(row.id)">
              <template #reference>
                <el-button type="primary" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <!-- paginatio
              v-model:current-page  分页器当前页码 
              v-model:page-size  每一页展示数据条数
              :page-sizes     用于设置下拉菜单设置
              background 分页器按钮背景颜色
              layout  设置分页器六个子组件布局
              size-change 下拉菜单发生变化
              current-change 页码发生变化
       -->
      <el-pagination @size-change="sizeChange" @current-change="getHasTrademark" :pager-count="9"
        v-model:current-page="pageNo" v-model:page-size="limit" :page-sizes="[3, 5, 7, 9]" :background="true"
        layout="prev, pager, next, jumper,->, sizes,total," :total="total" />
    </el-card>
    <!-- 对话框组件:添加品牌与修改品牌结构 -->
    <!-- v-model：控制对话框的显示与隐藏 true显示 false隐藏 
          title:标题 
     
     -->
    <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '修改品牌' : '添加品牌'">
      <el-form style="width: 80%;" :model="trademarkParams" :rules="rules" ref="formRef">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input placeholder="请你输入品牌名称" v-model="trademarkParams.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!-- upload组件
              action: 上传图片的接口,得带api不然服务器不发送请求
          
          -->
          <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

      </el-form>
      <!-- 具名插槽：footer -->
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang='ts' name='trademark'>
import { reqHasTrademark, reqAddOrUpdateTrademark, reqDeleteTrademark } from '@/api/product/trademark';
import { ref, onMounted, reactive, nextTick } from 'vue';
import type { Records, TradeMark, TradeMarkResponseData } from '@/api/product/trademark/type'
import { ElMessage, type UploadProps } from 'element-plus';
import useUserStore from '@/store/modules/user';
let userStore = useUserStore()
//分页器当前页码 
let pageNo = ref<number>(1)
// 每一页展示数据条数
let limit = ref<number>(3)
//存储已有商品总数
let total = ref<number>(0)
//存储已有商品数组
let trademarkArr = ref<Records>([])
//控制对话框的显示与隐藏
let dialogFormVisible = ref<boolean>(false)
//定义收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})

let formRef = ref()
//获取已有品牌接口封装为一个函数：
const getHasTrademark = async (pager = 1) => {
  pageNo.value = pager
  let result: TradeMarkResponseData = await reqHasTrademark(pageNo.value, limit.value)
  if (result.code == 200) {
    //存储已有商品总数
    total.value = result.data.total
    trademarkArr.value = result.data.records
  }
}
//页面挂载完毕先用一次
onMounted(() => {
  getHasTrademark()
})

//分页器页码发生变化时回调
//对于当前页码发生自定义事件时，组件pagination父组件回传了数据(当前页码)
// const changePageNo = ()=>{
//   getHasTrademark()
// }
//当下拉菜单发生变化时回调
//对于当前页码发生自定义事件时，组件pagination父组件回传了数据(当前下拉菜单数据)
const sizeChange = () => {
  getHasTrademark()
}

//添加品牌按钮
const addTrademark = () => {
  //开启对话框
  dialogFormVisible.value = true;
  //清空收集数据
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  //清空表单验证数据  第一次点击时dialog-form表单还未渲染
  // 第一种:
  // formRef.value?.clearValidate('tmName')
  // formRef.value?.clearValidate('logoUrl')
  //第二种
  nextTick(() => {
    formRef.value?.clearValidate('tmName')
    formRef.value?.clearValidate('logoUrl')
  })
}

//更新已有品牌按钮
// row即为当前已有品牌
const updateTrademark = (row: TradeMark) => {
  //清空表单验证数据  第一次点击时dialog-form表单还未渲染
  nextTick(() => {
    formRef.value?.clearValidate('tmName')
    formRef.value?.clearValidate('logoUrl')
  })

  //展示已有品牌数据
  // trademarkParams.tmName = row.tmName
  // trademarkParams.logoUrl = row.logoUrl
  // trademarkParams.id = row.id
  //ES6语法
  Object.assign(trademarkParams, row)
  //开启对话框
  dialogFormVisible.value = true;
}
//对话框取消按钮
const cancel = () => {
  dialogFormVisible.value = false
}
//对话框确认按钮
const confirm = async () => {
  //发请求之前，对整个表单进行校验 validate会返回一个promise对象
  await formRef.value.validate();

  let result: any = await reqAddOrUpdateTrademark(trademarkParams)
  //添加品牌成功
  if (result.code == 200) {
    console.log("success", result)
    dialogFormVisible.value = false
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    //再次发请求获得全部已有商品
    getHasTrademark(trademarkParams.id ? pageNo.value : 1)
  } else {
    //添加品牌失败
    console.log("error", result)
    dialogFormVisible.value = false
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败',
    })
  }



}

//上传图片->组件之前触发的函数 约束文件的类型大小等
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //要求:根式PNG|JPG|GIF 4M
  if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '文件过大,得小于4M'
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: "上传文件格式得为png|jpeg|gif"
    })
    return false
  }
}
//图片上传成功的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  //response:即为当前这次上传图片post请求成功后服务器返回的数据
  trademarkParams.logoUrl = response.data
  //图片上传成功，清楚对应图片校验结果
  formRef.value.clearValidate('logoUrl')
}
//品牌自定义校验规则
const validatorTmName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    //校验未通过返回信息
    callback(new Error('品牌名称大于等于两位'))
  }
}

const validatorLogoUrl = (rule: any, value: any, callback: any) => {
  //如果图片上传成功 则value为路径
  if (value) {
    callback()
  } else {
    callback(new Error('需要上传logo图片'))
  }
}
//表单校验规则对象
const rules = {
  tmName: [
    //required：这个字段务必校验，表单前面出来五角星
    { required: true, trigger: 'blur', validator: validatorTmName }
  ],
  logoUrl: [
    { required: true, trigger: 'change', validator: validatorLogoUrl }
  ],
}

//气泡确认框确认删除品牌回调
const removeTradeMark = async (id: number) => {
  //请求返回结果
  let result = await reqDeleteTrademark(id)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })
    //再次获得已有品牌数据
    getHasTrademark(trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败',
    })
  }
}

</script>


<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>